import React,{ useState,useEffect } from 'react';
import { Row, Col, Button, Space, Input, message } from 'antd';
import { connect, history } from 'umi';
import { scrollToAnchor } from '@/utils';
import Info from '../../accounts/child/info';
import TableInfo from '../../accounts/child/tableInfo';
import page from '../../page.less';
import { GlobalState } from '@/models/global';
import AdvancedModal from '@/components/Modal/AdvancedModal';
import styles from '../../styles.less';
import {getExtendedLease,postExtendedLease} from '@/service/fiance/index'
import {getDict} from '@/service/common/dict'

export interface FixedBarProps {
  global: GlobalState;
  dispatch: any;
  location: any;
}
function Details({ global: { currentRoute }, dispatch ,location}: FixedBarProps) {
  const [orderIds,setOrderIds] = useState('')
  const [delayNo,setDelayNo] = useState('')
  const [type,setType] = useState('')
  const routerName = () => {
    setOrderIds(location?.search?.split('id=')[1])
    setType(location?.search?.split('id=')[0])
  }
  const [allInfo,setAllInfo] = useState<any>({delayBatch:'',orderCarNo:'',id:"",companyName:'',driverName:'',
    plateNo:'',delayType:'',applyStartTime:'',applyEndTime:'',delayCount:'',rentAmount:'',delayStatus:'',
    delayStatusStr:'',handlerName:'',handleTime:'',handleRemark:''
  })
  const [stringInfo,setStringInfo] = useState('')
  const [dataRecord,setDataRecord] = useState<any[]>([])
  const [open, setOpen] = useState(false);
  const [idea, setIdea] = useState('');
  const [auditType, setAuditType] = useState<number>();
  const settlementInfo = [
    { label: '延租批次', value: allInfo?.delayBatch },
    { label: '订单编号', value: allInfo?.orderCarNo },
    { label: '延租单号', value: allInfo?.delayNo },
    { label: '所属公司', value: allInfo?.companyName },
    { label: '司机名称', value: allInfo?.driverName },
    { label: '车牌号', value: allInfo?.plateNo },
    { label: '租赁类型', value: allInfo?.rentName },
    { label: '租赁开始日', value: allInfo?.orderStartTime?.split(' ')[0] },
    { label: '租赁结束日', value: allInfo?.orderEndTime?.split(' ')[0] },
  ];

  const recordColumns = [
    { title: '操作人', dataIndex: 'logPersonname' },
    { title: '操作内容', dataIndex: 'logRemark' },
    { title: '操作时间', dataIndex: 'logTime' },
  ];
  const columns = [
    { label: '延租天数', value: allInfo?.delayCount },
    { label: '延租类型', value: stringInfo },
    { label: '延租日租金', value: allInfo?.rentAmount },
  ];
  const onModalConfirm = () => {
    const list = []
    list.push(delayNo)
    const data ={
      delayNo:list,
      delayStatus:auditType,
      handleRemark:idea,
    }
    postExtendedLease(data).then((res:any)=>{
      if(res?.success){
        message.success(res?.msg)
        history.goBack();
      }
    })
  };
  useEffect(()=>{
    routerName()
    getDict(
      {
        dictKeys: [
          'order_finance_delay_status',
        ],
      },
      (res:any) => {
        getExtendedLease({id:orderIds}).then((res2:any)=>{
          if(res2?.success){
            const res1 = {...res2}
            res?.order_finance_delay_status?.forEach((item:any)=>{
              if(item.dictKey===res1?.data?.delayStatus?.toString()){
                res1.data.delayStatusStr = item.dictValue
              }
            })
            setDelayNo(res1?.data?.delayNo)
            setAllInfo(res1?.data)
            if(res1?.data?.delayType===1){
              setStringInfo('无偿')
            }else{
              setStringInfo('有偿')
            }
            setDataRecord(res1?.data?.logListDtoList)
          }
        })
      },
    );
    
  },[orderIds])
  return (
    <div className={page.page}>
      <Row style={{ marginBottom: '15px' }}>
        <Space>
          <Button
            onClick={() => {
              scrollToAnchor('basic');
            }}
          >
            延租详情
          </Button>
          <Button
            onClick={() => {
              scrollToAnchor('info');
            }}
          >
            处理信息
          </Button>
          {allInfo?.logListDtoList?.length>0 &&
              <Button
                onClick={() => {
                  scrollToAnchor('operationRecord');
                }}
              >
                操作记录
              </Button>
          }
          
        </Space>
      </Row>

      <Info
        title="延租详情"
        info={settlementInfo}
        span={8}
        state={{ label: '处理状态', value: allInfo?.delayStatusStr }}
      />
      <Info
        title="延租申请"
        info={columns}
        span={8}
      />
        {/* 如果没有处理信息，则不显示 */}
      {allInfo?.handlerName &&
        <div className={`${page.page} ${page.card}`} id='info'>
        <div className={page.dotTitle}>处理信息</div>
        <Row gutter={24} className={page.rows}>
          <Col span={8} className={page.col}>
            <div className={page.label}>处理人员：</div>
            <div className={page.value}>{allInfo?.handlerName}</div>
          </Col>
          <Col span={8} className={page.col}>
            <div className={page.label}>处理时间：</div>
            <div className={page.value}>{allInfo?.handleTime}</div>
          </Col>
          <Col span={24} className={page.col}>
            <div className={page.label}>处理状态：</div>
            <div className={page.value}>{allInfo?.delayStatusStr}</div>
          </Col>
          <Col span={24} className={page.col}>
            <div className={page.label}>处理意见：</div>
            <div className={page.value}>{allInfo?.handleRemark}</div>
          </Col>
        </Row>
      </div>
      } 
      {/* 如果没有操作记录，则不显示 */}
      {allInfo?.logListDtoList?.length>0 &&
          <TableInfo
            id="operationRecord"
            title="操作记录"
            columns={recordColumns}
            dataSource={dataRecord}
          />
      }
     
      <Row justify="center" style={{ marginTop: '20px' }}>
        {/* 不同状态显示不同的按钮 */}
        <Space>
          <Button
            shape="round"
            onClick={(e) => {
              e.stopPropagation();
              dispatch({
                type: 'global/deleteTabs',
                payload: currentRoute,
              });
              history.goBack();
            }}
          >
            关闭
          </Button>
          {type==='?type?' &&
            <>
              <Button
                shape="round"
                style={{ border: '1px solid #FDC12E', color: '#FDC12E' }}
                onClick={() => {
                  setAuditType(0);
                  setOpen(true);
                }}
              >
                拒绝延租
              </Button>
              <Button
                shape="round"
                type="primary"
                onClick={() => {
                  setAuditType(1);
                  setOpen(true);
                }}
              >
                同意延租
              </Button>
            </>
          }
         
        </Space>
      </Row>
      <AdvancedModal
        isOpen={open}
        title="延租审核"
        setIsOpen={setOpen}
        footer={null}
      >
        <Row>
          <Col span={24} className={`${styles.flex} ${styles.row}`}>
            {auditType === 0 && '拒绝延租'}
            {auditType === 1 && '同意延租'}
          </Col>
          <Col span={24} className={`${styles.flex} ${styles.row}`}>
            处理意见：
            <Input.TextArea
              allowClear
              showCount
              maxLength={200}
              placeholder="请输入处理意见，不超过200个字符"
              onChange={({ target: { value } }) => {
                setIdea(value);
              }}
              defaultValue={idea}
            />
          </Col>
        </Row>
        <Row justify="center">
          <Space>
            <Button onClick={() => setOpen(false)}>关闭</Button>
            <Button type="primary" onClick={onModalConfirm}>
              确定
            </Button>
          </Space>
        </Row>
      </AdvancedModal>
    </div>
  );
}
export default connect(({ global }: any) => ({ global }))(Details);
